# -*- coding: utf-8 -*-
"""
Created on Wed Aug 14 13:02:29 2019

@author: haodong
"""

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import metrics
from sklearn.linear_model import LogisticRegression

df=pd.read_csv('imbalance.csv',header=None)


df.columns = ["x1", "x2","y"]
features=["x1","x2"]
labels = ["y"]


# 原始方法，不调整权重
model = LogisticRegression(C=1e4)
model.fit(df[features], df[labels])

pred = model.predict(df[features])

pred=pd.DataFrame(pred)
pred.columns=['pred']
print(metrics.classification_report(df['y'],pred))

#加权方法

y=df['y']

#加权方法一，使用比例的倒数手动调节权重
positiveWeight = len(y[y>0]) / float(len(df['y']))
classWeight = {1: 1. / positiveWeight, 0: 1. / (1 - positiveWeight)}
# 为了消除惩罚项的干扰，将惩罚系数设为很大
model1 = LogisticRegression(class_weight=classWeight, C=1e4)
model1.fit(df[features], df[labels])
pred1=model1.predict(df[features])
pred1=pd.DataFrame(pred1)
print(metrics.classification_report(df['y'],pred1))

metrics.confusion_matrix(df['y'],pred1)


#加权方法二，balanced方法
model2 = LogisticRegression(class_weight='balanced', C=1e4)
model2.fit(df[features], df[labels])
pred2=model2.predict(df[features])
pred2=pd.DataFrame(pred2)
print(metrics.classification_report(df['y'],pred2))
metrics.confusion_matrix(df['y'],pred2)

y_prob = model2.predict_proba(df[features])[:,1]

fpr, tpr, threshold = metrics.roc_curve(df['y'], y_prob)
auc = metrics.auc(fpr, tpr)
